var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
//修改id缓存，传递分组参数
function checkGroup(checkId,el) {
    console.log(el);
    sessionStorage.setItem("checkId",checkId);
    web.role_list();
}
function delete_roleId(roleId) {
    layer.confirm('确认要删除此角色组吗？',function () {
        $.ajax({
            type: "POST",
            url: root.accessInter.access_role_deleteRole,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                ROLE_ID:roleId
            },  //传入组装的参数
            success: function (data) {
                switch (data.code) {
                    case 200:
                        layer.msg(data.data.errors[0], {icon: 1, time: 1000});
                        var index =  location.reload();
                        parent.layer.close(index);
                    case 400:
                        layer.msg(data.data.errors[0], {icon: 1, time: 1000});
                    case 404:
                        layer.msg(data.data.errors[0], {icon: 1, time: 1000});
                }
            },
        });
    })
}
var allList;
web.role_list=(function(){
    return function(page,current,obj,scrollLoad){
        var user_data = {
            ROLE_ID: sessionStorage.getItem("checkId")
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            $(".removeEl").remove();//清空分组
            dataSource.splice(0,dataSource.length);//清空数组
            allList=data.roleList;
            for(var i=0;i<data.roleList.length;i++){
                if (i<7){
                    if(data.roleList[i].ROLE_NAME== '系统管理'){
                        if(data.pd!=undefined && data.roleList[i].ROLE_ID==data.pd.ROLE_ID){
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="f-l mb-15 btn radius size-S mr-10 removeEl current" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div></div>')
                        }
                        else{
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="f-l mb-15 btn radius size-S mr-10 removeEl" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div></div>');
                        }
                    }
                    else {
                        if(data.pd!=undefined && data.roleList[i].ROLE_ID==data.pd.ROLE_ID)
                        {$(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="f-l mb-15 btn' +
                            ' radius size-S mr-10 removeEl current" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div>&nbsp;<a href="##" class="Hui-iconfont powerButton 477" onclick="edit_roleId(\'修改信息\',\'group_add.html\',\''+ data.roleList[i].ROLE_ID+ '\',\''+ data.roleList[i].ROLE_NAME+ '\')" style="float: left;">&#xe6df;</a><a style="float: left;" href="##" class="Hui-iconfont powerButton 478" onclick="delete_roleId(\''+ data.roleList[i].ROLE_ID+ '\')">&#xe6a6;</a></div>')
                        }
                        else{
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="f-l mb-15 btn radius size-S mr-10 removeEl" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div>&nbsp;<a href="##" class="Hui-iconfont powerButton 477" onclick="edit_roleId(\'修改信息\',\'group_add.html\',\''+ data.roleList[i].ROLE_ID+ '\',\''+ data.roleList[i].ROLE_NAME+ '\')" style="float: left;">&#xe6df;</a><a style="float: left;" href="##" class="Hui-iconfont powerButton 478" onclick="delete_roleId(\''+ data.roleList[i].ROLE_ID+ '\')">&#xe6a6;</a></div>');
                        }

                    }
                } else {
                    if(data.roleList[i].ROLE_NAME== '系统管理'){
                        if(data.pd!=undefined && data.roleList[i].ROLE_ID==data.pd.ROLE_ID){
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="ROLE_GROUP f-l mb-15 hide btn radius size-S mr-10 removeEl current" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div></div>')
                        }
                        else{
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="ROLE_GROUP f-l mb-15 hide btn radius size-S mr-10 removeEl" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div></div>');
                        }
                    }
                    else {
                        if(data.pd!=undefined && data.roleList[i].ROLE_ID==data.pd.ROLE_ID)
                        {$(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="ROLE_GROUP f-l hide mb-15 btn' +
                            ' radius size-S mr-10 removeEl current" onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div>&nbsp;<a href="##" class="Hui-iconfont" onclick="edit_roleId(\'修改信息\',\'group_add.html\',\''+ data.roleList[i].ROLE_ID+ '\',\''+ data.roleList[i].ROLE_NAME+ '\')" style="float: left;">&#xe6df;</a><a style="float: left;" href="##" class="Hui-iconfont powerButton 478" onclick="delete_roleId(\''+ data.roleList[i].ROLE_ID+ '\')">&#xe6a6;</a></div>')
                        }
                        else{
                            $(".roleGroup").append('<div  id="ROLE_GROUP" title="'+data.roleList[i].ROLE_NAME+'" class="ROLE_GROUP f-l hide mb-15 btn radius size-S mr-10 removeEl " onclick="checkGroup(\''+ data.roleList[i].ROLE_ID+ '\',this)"><div style="padding-bottom: 2px;width: 74px;height:22px;overflow: hidden;float: left;">'+data.roleList[i].ROLE_NAME+'</div>&nbsp;<a href="##" class="Hui-iconfont" onclick="edit_roleId(\'修改信息\',\'group_add.html\',\''+ data.roleList[i].ROLE_ID+ '\',\''+ data.roleList[i].ROLE_NAME+ '\')" style="float: left;">&#xe6df;</a><a style="float: left;" href="##" class="Hui-iconfont powerButton 478" onclick="delete_roleId(\''+ data.roleList[i].ROLE_ID+ '\')">&#xe6a6;</a></div>');
                        }

                    }
                }
                power();

            }

            $.each(data.roleList_z, function (i, field) {
                var rowData = new Array();
                rowData.push(field.ROLE_NAME);
                rowData.push(field.ROLE_DESCRIPTION);
                rowData.push(field.USERNAME);
                rowData.push(field.CREAT_TIME);
                rowData.push(field.STATUS);
                rowData.push(field.ROLE_ID);
                rowData.push(field.RIGHTS);
                rowData.push(field.NAME);
                dataSource.push(rowData);
            });
            function removeArrEl(dataArr) {
                for(var i = 0; i < dataArr.length - 1; i++) {
                    for(var j = i + 1; j < dataArr.length; j++) {
                        if(dataArr[i][5] == dataArr[j][5]) {
                            dataArr.splice(j, 1);
                            j--;
                        }
                    }
                }
                return dataArr;
            }
            dataSource = removeArrEl(dataSource);
            initDataTable(dataSource);
            function initDataTable(dataSource) {
                var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
                dttable.fnClearTable(); //清空一下table
                dttable.fnDestroy(); //还原初始化了的datatable

                $("#datatable").DataTable({
                    "fnDrawCallback" : function(){
                        this.api().column(0).nodes().each(function(cell,i){
                           /* cell.innerHTML = i+1;*/
                            //权限控制函数
                            power()
                        });
                    },
                    "autoWidth": false,
                    "ordering": true,
                    "searching": true,
                    "paging": true,
                    "retrieve": true,
                    "destroy": true,
                    "bAutoWidth": true,
                    "bLengthChange": true,
                    "bSort": true,
                    "aaSorting": [[3,'desc'],],//数据排序
                    "aLengthMenu":[10,20,30],
                    "oLanguage": {
                        "sLengthMenu": "每页显示 _MENU_ 条记录",
                        "sZeroRecords": "抱歉， 没有找到",
                        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                        "sInfoEmpty": "没有数据",
                        "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "前一页",
                            "sNext": "后一页",
                            "sLast": "尾页"
                        },
                        "sZeroRecords": "没有检索到数据",
                        "sProcessing": "<img src='./loading.gif' />"
                    },
                    data: dataSource,
                    columnDefs: [
                        {
                            "visible": true,
                            "targets": 0
                        },
                        {
                            "render": function(data,type,row,meta){
                                var val = '<div style="width: 60px;height:20px;overflow: hidden;margin: auto;" title="'+row[0]+'">'+row[0]+'</div>';
                                return val;
                            },
                            "targets": 0
                        },
                        {
                            "render": function(data,type,row,meta){
                                var val = '<div style="padding-bottom: 2px;width: 350px;height:40px;overflow: hidden;">'+row[1]+'</div>';
                                return val;
                            },
                            "targets": 1
                        },
                        {
                            "render": function(data,type,row,meta){
                                if(row[0]=='员工'){
                                    var val = '全部账号';
                                    return val
                                }
                                else{
                                    if(row[7] == undefined||row[2] == undefined){
                                        var val = '';
                                    }else {
                                        var val = '<span class="dropDown"><a class="a_remove"><div  class="codeWrap"  onmouseover="getCodeList(\''+row[5]+'\')" >'+row[2]+'('+row[7]+')</div></a></span>';
                                    }
                                    return val;
                                }
                                return val
                            },
                            "targets": 2
                        },
                        {
                            "render": function(data,type,row,meta){
                                if(row[0]=='员工'){
                                    var val = '<a><span class="list powerButton 484" onclick="role_stop(\'权限设置\',\'menu.html\',\''+row[5]+'\')">权限设置</span></a>';
                                    return val
                                }else if(row[0]=='门店操作员'){
                                    var val = '<a><span class="list powerButton 484" onclick="role_stop(\'权限设置\',\'menu.html\',\''+row[5]+'\')">权限设置</span>&nbsp;&nbsp;<span class="list powerButton 482" onclick="role_from(\'所属账号\',\'role_from.html\',\''+row[5]+'\')">所属账号</span></a>';
                                    return val;
                                }
                                else
                                {var val = '<a><span class="list powerButton 481" onclick="ood_edit(\'修改信息\',\'role_add.html\',\''+row+'\')">编辑</span>&nbsp;&nbsp;<span class="list powerButton 484" onclick="role_stop(\'权限设置\',\'menu.html\',\''+row[5]+'\')">权限设置</span>&nbsp;&nbsp;<span class="list powerButton 482" onclick="role_from(\'所属账号\',\'role_from.html\',\''+row[5]+'\')">所属账号</span>&nbsp;&nbsp;<span a href="##" class="list powerButton 483" onclick="delete_roleId(\''+ row[5]+'\')">删除角色</span></a>';
                                    return val;}
                            },
                            "targets": 5
                        },
                        {
                            "render": function(data,type,row,meta){
                                if(row[0]=='员工'){
                                    var val = '<span class=" powerButton 480"> <a class="dropDown_A" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">开启</a></span>';
                                    return val;
                                }else if(row[4]=="0"){
                                    var val = '<span class=" powerButton 480"> <a class="dropDown_A powerButton 480" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">开启<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="user_stop(\'\',\''+ row[5] +'\')"><a href="#">禁用</a></li></ul></span>';
                                    return val;
                                }else if(row[4]=="1") {
                                    var val = '<span class=" powerButton 480"> <a class="dropDown_A powerButton 480" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">禁用<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="user_start(\'\',\''+ row[5] +'\')"><a href="#">开启</a></li></ul></span>';
                                    return val;
                                }
                            },
                            "targets": 4
                        },
                    ]
                });
                power();
            };
        };
        return web.doAjax(root.accessInter.access_role_listRolesApi,'post',user_data, succCallBack);
    }
})();
//角色组收起展开
var iClick2=0
$('.rolegroup_box .btn_open').click(function(){
    iClick2++;
    if(iClick2%2!=0){
        console.log($('.ROLE_GROUP'))
        $('.ROLE_GROUP').removeClass('hide');
        $(".btn_open span").html("收起");
    }else{
        $('.ROLE_GROUP').addClass('hide');
        //$("#more").attr("class", "hidden");
        //$("#less").attr("class", "lessAdd")
        $(".btn_open span").html("展开");
    }
})

function getCodeList(id) {
    var user_data = {
        ROLE_ID: id
    }
    var succCallBack = function (data, status, response) {
        var datacunko = []
        if(data.userList == undefined){
                var datacunko = '';
            }else {
                   for (var i = 0; i < data.userList.length; i++) {
                    datacunko += data.userList[i].NAME + '(' + data.userList[i].USERNAME + ')' + '  ';
            }
            $('.codeWrap').attr("title",  datacunko)
        }
    };
     web.doAjax(root.accessInter.access_role_listUser, 'post', user_data, succCallBack);
}
getCodeList();

function edit_roleId(title,url,roleId,roleName) {
    console.log()
    sessionStorage.setItem("groupId",roleId);
    sessionStorage.setItem("groupName",roleName);
    sessionStorage.setItem("groupEdit",true);

    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
function role_from(title,url,row){
    window.session_storage.setItem("roleId_to_roleForm",row);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//=====================================================================================================================
/*停用*/
function user_stop(obj,id){
    layer.confirm('确认要停用吗？',function(index){
        console.log(id)
        $.ajax({
            type: "POST",
            url: root.accessInter.access_role_editS,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                ROLE_ID: id,
                STATUS: "1"
            },  //传入组装的参数
            success: function (result) {
                console.log(result);
                layer.msg(result.message,{icon: 5,time:1000},function () {
                    window.location.reload();
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    });
}

/*启用*/
function user_start(obj,id){
    layer.confirm('确认要启用吗？',function(index){
        $.ajax({
            type: "POST",
            url: root.accessInter.access_role_editS,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                ROLE_ID: id,
                STATUS: "0"
            },  //传入组装的参数
            success: function (result) {
                console.log(result);
                layer.msg(result.message,{icon: 6,time:1000},function () {
                    window.location.reload();
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    });
}
